﻿using System.Text.Json;

namespace dotnet_ef_admin.Src.Extensions;

public static class MiddlewareExtensions {
    public static void UseValidateIdMiddleware(this IApplicationBuilder app) {
        app.Use(async (context, next) => {
            // 检查请求方法是否为DELETE或GET
            if (context.Request.Method == HttpMethods.Delete || context.Request.Method == HttpMethods.Get) {
                // 尝试从路由值中获取'id'参数
                var idParam = context.Request.RouteValues.TryGetValue("id", out var value) ? value?.ToString() : null;

                // 验证'id'参数是否为有效的整数
                if (idParam != null && !int.TryParse(idParam, out _)) {
                    // 设置响应状态码为400（错误请求）
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;

                    // 向客户端返回错误信息
                    await context.Response.WriteAsync("参数'id'必须是有效的整数。");

                    // 不再调用后续中间件
                    return;
                }
            }

            // 调用下一个中间件继续处理请求
            await next.Invoke();

            // 添加自定义中间件来处理 405 错误
            if (context.Response.StatusCode == StatusCodes.Status405MethodNotAllowed) {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
                var result = JsonSerializer.Serialize(new {
                    code = -1,
                    data = (object?)null,
                    msg = "请求的方法不被允许。"
                });
                await context.Response.WriteAsync(result);
            }
        });
    }
}